package com.ivan.toolkit.common;

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

import lombok.extern.log4j.Log4j2;

@Log4j2
public class AtFile {
	
	private File file = null;
	
	public static AtFile getUserDir() {
		return get(System.getProperty("user.dir"));
	}
	
	public static AtFile get(String pathname) {
		return get(new File(pathname));
	}
	
	public static AtFile get(File file) {
		return new AtFile(file);
	}
	
	private AtFile(File file) {
		this.file = file;
	}
	
	public File file() {
		return file;
	}
	
	public AtFile child(String childName) {
		return new AtFile(new File(file, childName));
	}
		
	public void keepMaxFileCount(int count) {
		
		if(file.isDirectory()) {
			
			File[] files = file.listFiles();
			if(files != null && files.length > count) {
				
				Arrays.sort(files, new Comparator<File>() {
	
					@Override
					public int compare(File file, File newFile) {
						if(file.lastModified() > newFile.lastModified()) {
							return 1;
						} else if(file.lastModified() == newFile.lastModified()) {
							return 0;
						} else {
							return -1;
						}
					}
				});
					
				for(int i = 0; i < files.length - count; i++) {
					files[i].delete();
					files[i].deleteOnExit();
				}
									
				
			}
			
		}
		
	}

	public void keepMaxTotalLength(long maxLength) {
		
		if(file.isDirectory()) {
			
			long total = 0;
			File[] files = file.listFiles();
			if(files != null) {
				for(File file : files) {
					total += file.length();
				}
			}
			
			log.info("total size: " + total + "byte");
			log.info("limit size: " + maxLength + "byte");
			
			if(total > maxLength) {
				
				Arrays.sort(files, new Comparator<File>() {

					@Override
					public int compare(File file, File newFile) {
						if(file.lastModified() > newFile.lastModified()) {
							return 1;
						} else if(file.lastModified() == newFile.lastModified()) {
							return 0;
						} else {
							return -1;
						}
					}
				});
				
				
				log.info("Stored data is bigger then limit, Guarding......");
				
				for(File f : files) {
					
					log.info(" Delete file:" + f.getName() + " size:" + f.length());
					
					total -= f.length();
					
					f.delete();
					
					if(total <= maxLength) {
						break;	
					}
				}
				
				log.info("New stored data total: " + total);
				
			}
			
		}
		
		
	}

}
